package com.ym521.emojipack.install;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ym521.emojipack.EmojiPackHelper;
import com.ym521.emojipack.widget.EmojiPackEditText;
import com.ym521.emojipack.widget.EmojiPackMultiAutoCompleteTextView;
import com.ym521.emojipack.widget.EmojiPackTextView;

/**
 * @author Ym
 */
public final class EmojiPackLayoutInflaterFactory implements LayoutInflater.Factory2 {
    private final EmojiPackHelper.Builder builder;

    public EmojiPackLayoutInflaterFactory(EmojiPackHelper.Builder builder) {
        this.builder = builder;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
        View view = builder.activity.getDelegate().createView(null,name, context, attrs);
        if (view instanceof EmojiPackTextView
                || view instanceof EmojiPackEditText
                || view instanceof EmojiPackMultiAutoCompleteTextView) {
            return view;
        }

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            try {
                view = inflater.createView(name, null, attrs);
            } catch (Exception ignored) {
            }
        }

        if (view instanceof TextView) {
            TextView textView = (TextView) view;
            textView.addTextChangedListener(new EmojiPackTextWatcher(textView, builder));
        }
        return view;
    }
    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        View view = builder.activity.getDelegate().createView(parent, name, context, attrs);
        if (view instanceof EmojiPackTextView
                || view instanceof EmojiPackEditText
                || view instanceof EmojiPackMultiAutoCompleteTextView) {
            return view;
        }

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            try {
                view = inflater.createView(name, null, attrs);
            } catch (Exception ignored) {
            }
        }

        if (view instanceof TextView) {
            TextView textView = (TextView) view;
            textView.addTextChangedListener(new EmojiPackTextWatcher(textView, builder));
        }
        return view;
    }

}
